<?php

namespace App\ModelFilters;

use EloquentFilter\ModelFilter;

class QHSchoolSpecFilter extends ModelFilter
{
    /**
    * Related Models that have ModelFilters as well as the method on the ModelFilter
    * As [relationMethod => [input_key1, input_key2]].
    *
    * @var array
    */
    public $relations = [];

    public function province($v) {
        if (request()->is('admin/*')) {
            $v = is_array($v) ? $v : explode(',', $v);

            if (!empty($v)) {
                return $this->query->where(function ($query) use ($v) {
                    foreach ($v as $value) {
                        $query->orWhereRaw("CONCAT(',', province, ',') LIKE ?", [',%' . $value . '%,']);
                    }
                });
            }
        }
        // return $this->whereRaw('province like ? OR province IS NULL', ["%$v%"]);
        return $this->where('province', 'like', '%'.$v.'%');
    }

    public function name($v) {
        return $this->where('name', 'like', '%'.$v.'%')->orWhere('code', $v);
    }

    public function key($v) {
        return $this->where('name', 'like', '%'.$v.'%')->orWhere('code', $v);
    }

    public function class($v) {
        return $this->whereIn('class', array_filter(explode(',', $v)));
    }

    public function schoolId($v) {
        return $this->whereHas('school', function ($q) use ($v){
            return $q->where('schoolId', $v);
        });
    }

    public function type($v) {
        return $this->where('type', $v);
    }

    public function bxType($v) {
        return $this->where('bxType', $v);
    }

    public function level($v) {
        return $this->where('level', $v);
    }

    public function level2($v) {
        $v = explode(',', $v);
        return $this->whereHas('parent', function ($q) use ($v) {
           $q->whereIn('name', $v)->where('level', 2);
        });
    }
}
